# -*- coding: utf-8 -*-

# graphic-pppoe-client - Easy graphic networking manager
#
# Author: GoTLiuM InSPiRiT <gotlium@gmail.com>
#
# Copyright 2010, GoTLiuM InSPiRiT <gotlium@gmail.com>.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE.  See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program.  If not, see <http://www.gnu.org/licenses/>.

from re import findall
from libraries.fs import fileExists, getFile, putFile
from libraries.los import system

class PPPD(object):

	tplName = None

	auth_file = '/etc/ppp/%s-secrets'
	conn_file = '/etc/ppp/peers/gp%s'
	tmpl_file = './templates/%s'
	auth_type = ('chap', 'pap')
	auth_str = '"%s" * "%s"'

	def setPassword(self, login, password):
		for type in self.auth_type:
			filename = self.auth_file % type
			authStr = self.auth_str % (str(login), str(password))
			srchStr = authStr.replace('*', '\*')
			if fileExists(filename):
				content = getFile(filename)
				if not findall(srchStr, content):
					content += "\n%s" % authStr
					putFile(filename, content)
				del content
		return True

	def delPassword(self, login, password, content = ""):
		for type in self.auth_type:
			filename = self.auth_file % type
			srchStr = self.auth_str % (str(login), str(password))
			if fileExists(filename):
				for line in getFile(filename).split("\n"):
					line = line.strip()
					if line != srchStr and line != "":
						content += "%s\n" % line
				if content != "":
					putFile(filename, content)
		return True

	def generateConnectionFromTemplate(self, data, connId):
		templateFile = self.tmpl_file % self.tplName
		if fileExists(templateFile):
			content = getFile(templateFile)
			for key in data.keys():
				content.replace(key, data[key])
			return putFile(conn_file % str(connId), content)

	def findPppd(self):
		paths = ("/usr/local/sbin/pppd", "/usr/sbin/pppd", "/sbin/pppd")
		for file in paths:
			if fileExists(file):
				return file
		return 'pppd'

	def runPppd(self, connId):
		pppd = findPppd()
		tmpl = 'gp%d' % connId
		log = '/tmp/' % tmpl
		cmd = 'nohup %s call %s nodetach unit %d >& %s &' % (pppd, tmpl, 10, log)
		system(cmd)

	def getInfo(self, connId):
		tmpl = 'gp%d' % connId
		log = '/tmp/' % tmpl
		for s in open(log).readlines():
			if s.find('<-->') != -1:
				ifName = s.split(':')[1].strip().split(' ')[0]
				break
		pid = system("ps aux | grep -e '%s$' | awk '{print $2}'" % (tmpl, connId))
		return (ifName, pid)
